<template>
    <div class="count-down">
        <span class="times shadow1">{{data.h}}</span>
        <span class="space" :class="{'font-color':fontColor}">:</span>
        <span class="times shadow2">{{data.m}}</span>
        <span class="space" :class="{'font-color':fontColor}">:</span>
        <span class="times shadow3">{{data.s}}</span>
    </div>
</template>

<script>
export default {
    name: 'CountDown',
    props: {
        time: {
            type: Object,
            default: () => {
                return {
                    h: '00',
                    m: '00',
                    s: '00'
                }
            }
        },
        fontColor: {
            type:Boolean,
            default: false
        }
    },
    data() {
        return {
            timer: '',
            data: this.time,
        }
    },
    computed: {
    },
    methods: { 
        // 倒计时
        _countDown() {
            let hh = parseInt(this.data.h)
            let mm = parseInt(this.data.m)
            let ss = parseInt(this.data.s)
            if (hh === 0 && mm === 0 && ss === 0) {
                clearInterval(this.timer)
                return
            }
            if (ss === 0) {
                if (mm === 0) {
                    hh--
                    mm = 60
                }
                mm--
                ss = 60
            }
            ss--
            this.data = {
                h: this._padLeft(hh),
                m: this._padLeft(mm),
                s: this._padLeft(ss)
            }
        },
        // 确保时分秒为两位数
        _padLeft(str) {
            str = '00' + str
            return str.substr(str.length - 2, 2);
        }
    },
    mounted() {
        this.timer = setInterval(this._countDown, 1000)
    },
    watch: {
        'time'() {
            this.data = this.time
        }
    },
     beforeDestroy() {
        if(this.timer) { //如果定时器还在运行 或者直接关闭，不用判断
            clearInterval(this.timer); //关闭
        }
    }
}
</script>